package org.wii.base.part;

import com.google.common.util.concurrent.SimpleTimeLimiter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 调用控制类
 * @author tanghong on 2022/12/22
 */
@Slf4j
public class IWiiCallCtrl {
    /**
     * 调用控制类
     * @param callable 调用函数
     * @param timeout 超时时间(毫秒)
     * @return 结果
     * @throws Exception
     */
    public <T> T callCtrl(Callable<T> callable, long timeout) throws Exception{
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        SimpleTimeLimiter simpleTimeLimiter = SimpleTimeLimiter.create(executorService);
        try {
            return simpleTimeLimiter.callWithTimeout(callable, timeout, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("超时调用控制异常!", e);
            throw e;
        } finally {
            executorService.shutdown();
        }
    }

    /**
     * 调用控制类
     * @param runnable 执行代码
     * @param timeout 超时时间(毫秒)
     * @throws Exception
     */
    public void callCtrl(Runnable runnable, long timeout) throws Exception{
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        SimpleTimeLimiter simpleTimeLimiter = SimpleTimeLimiter.create(executorService);
        try {
            simpleTimeLimiter.runWithTimeout(runnable, timeout, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("超时调用控制异常!", e);
            throw e;
        } finally {
            executorService.shutdown();
        }
    }
}
